import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import {
  createBrowserRouter,
  RouterProvider,
  Navigate,
} from "react-router-dom";
import "antd/dist/reset.css";
import { Provider } from "react-redux";
import { store } from "./store/store";
import App from "./App.tsx";
import Home from "./pages/Home";
import About from "./pages/About";
import Login from "./pages/Login";
import Portal from "./pages/Portal";
import Context from "./pages/Context/";

// 创建路由守卫高阶组件
function AuthGuard({ children }: { children: React.ReactNode }) {
  const { username } = store.getState().auth; // 直接获取当前store状态

  if (!username) {
    return <Navigate to="/login" replace />;
  }

  return <>{children}</>;
}

const router = createBrowserRouter([
  {
    path: "/",
    element: <Navigate to="/login" replace />,
  },
  {
    path: "/login",
    element: <Login />,
  },
  {
    path: "/app",
    element: (
      <AuthGuard>
        <App />
      </AuthGuard>
    ),
    children: [
      {
        index: true,
        element: <Navigate to="/app/home" replace />,
      },
      {
        path: "home",
        element: <Home />,
      },
      {
        path: "about",
        element: <About />,
      },
      {
        path: "portal",
        element: <Portal />,
      },
      {
        path: "context",
        element: <Context />,
      },
    ],
  },
]);

createRoot(document.getElementById("root")!).render(
  <StrictMode>
    <Provider store={store}>
      <RouterProvider router={router} />
    </Provider>
  </StrictMode>
);
